import React, { Component } from 'react';
import {
	StyleSheet,
	Text,
	View,
	Platform,
	Image,
	TouchableOpacity,
	WebView,
	DeviceEventEmitter,
	Animated,
	PanResponder
} from "react-native";
import request from './request';
import { style } from '../../theme/style';
import { GLOBAL } from '../../config/global';
import { ScrollTabView } from '../../component/ScrollTabView';
import { ImgWidthTextButton } from '../../component/ImgWidthTextButton';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { ListDailogModal } from '../../component/ListDailogModal';
import { Common } from '../../component/common/Common';
import SelectComponent from './_component/SelectComponent';
import { BoxShadow } from 'react-native-shadow';
import ToastUtil from '../../utils/toast';

const scale = GLOBAL.SCALE;
const starEmpty = require('../../imgs/report/starYellowEmpty.png');
const starYellew = require('../../imgs/report/starYellow.png');
const filter = require('../../imgs/report/filter-new.png');
const bottomImg = require('../../imgs/report/bottomType.jpg');
let that;
let ifCollect;
let rptName;
let rptId;
let navData;
let sendData = {};
const shadowOpt = {
	width: GLOBAL.SCREEN_WIDTH,
	height: 34 * scale,
	color: "#000",//阴影颜色
	border: 6 * scale,//阴影宽度
	radius: 0 * scale,//包裹的子元素圆角多少这里必须是多少
	opacity: 0.1,//透明度
	x: 0,
	y: 0,
}
export class ReportDetailPage extends Component {
	constructor(props) {
		super(props);
		this.state = {
			collectStatus: 0,
			webViewUrl: '',
			filterWebViewUrl: '',
			filterData: '',//查询条件
			_isLoad: false,
			rptTypesModal: false,
			rptFilterModal: false,
			left: 0
		}
		this.reportsList = this.props.navigation.state.params.reportsList;
		that = this;
	}

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerRight: (
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginRight: 17 }}>
					<TouchableOpacity style={{ marginRight: 17 * scale }} activeOpacity={1}
						onPress={() => {
							that._collect(rptId);
						}}>
						<Image source={ifCollect ? starYellew : starEmpty} style={{ width: 18 * scale, height: 18 * scale }} />
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={1}
						onPress={() =>
							that.toggleFilterModal(rptId)
						}>
						<Image source={filter} style={{ width: 22 * scale, height: 18 * scale }} />
					</TouchableOpacity>
				</View >
			),
			headerTitle: rptName ? rptName : '报表详情',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerTintColor: style.color.white,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				textAlign: 'center',
			}
		}
	}

	componentWillMount () {
		this.initPage();

		//绑定手势事件
		this._panResponder = PanResponder.create({
			onStartShouldSetPanResponder: () => true,
			onMoveShouldSetPanResponder: () => true,
			onPanResponderGrant: () => {
				this._left = this.state.left
			},
			onPanResponderMove: (evt, gs) => {
				this.setState({
					left: this._left + gs.dx
				})
			},
			onPanResponderRelease: (evt, gs) => {
				console.log('release');
				this.setState({
					left: this._left + gs.dx
				})
			}
		})
	}

	componentWillUnmount () {
		DeviceEventEmitter.emit('reportIndex');
		//离开当前场景，清楚数据
		ifCollect = null;
		rptName = null;
		rptId = null;
	}

	//初始化,默认第一种类型的第一个报表详情，因返回数组的第一个类型是收藏，所以实际要查询第二类的第一个报表
	initPage () {
		let filterInfoBoxWidth = new Animated.Value(0 * scale);
		let filterInfoOpenWidth = GLOBAL.SCREEN_WIDTH;

		this._getReportList();

		this.setState({
			filterInfoBoxWidth,
			filterInfoOpenWidth
		})
	}

	//获取报表列表
	async _getReportList () {
		let reportsList = await request.getReportList();
		reportsList && this.setHeaderInfo(reportsList[1].rptDeployVOList[0].rptId, reportsList[1].rptDeployVOList[0].rptName, reportsList[1].rptDeployVOList[0].attentionFlag);
		reportsList && this._setUrl(reportsList[1].rptDeployVOList[0].rptId);


		//数据处理，用于显示底部弹出筛选组件
		reportsList = reportsList && reportsList.map((item, index) => {
			//上拉弹框默认选中第一个报表
			if (index === 1) {
				item.rptDeployVOList[0].selected = true;
			}
			return {
				typeId: item.rptTypeVO.typeId,
				typeName: item.rptTypeVO.typeName,
				children: item.rptDeployVOList,
			}
		})


		//获取收藏报表
		const collectList = await request.getCollectList();
		if (collectList) {
			reportsList[0].typeName = '收藏';
			reportsList[0].children = collectList.rows;
			reportsList[0].children.map((item, j) => {
				item.attentionFlag = 1;
			})
		} else {
			reportsList[0].typeName = '收藏';
			reportsList[0].children = [];
		}
	}

	//点击屏幕关闭弹框
	_dimissModal () {
		this.setState({
			reportsList,
			curRptId: this.state.curRptId ? this.state.curRptId : reportsList[1].children[0].rptId,
			curRptName: this.state.curRptName ? this.state.curRptName : reportsList[1].children[0].rptName,
			attentionFlag: this.state.attentionFlag ? this.state.attentionFlag : reportsList[1].children[0].attentionFlag,
		})

	}

	async _setUrl (id) {
		const response = await this._getDetail(id);
		let webViewUrl = response.resultUrl + this.state.filterData
		let filterWebViewUrl = response.initUrl + this.state.filterData
		this.setState({
			webViewUrl,
			filterWebViewUrl
		});
	}

	async _getDetail (id) {
		const detail = await request.getReportDetail(id);
		if (detail) {
			this.props.navigation.navigate('ReportDetailPage', { item: detail })
		}
	}

	//刷新params  头部信息
	setHeaderInfo = (id, name, flag) => {
		const navigation = this.props.navigation;
		rptName = name;
		rptId = id;
		ifCollect = flag ? 1 : 0;
		navigation.setParams({ status: rptId, status: rptName, status: ifCollect })  //实时更新头部信息
	}

	// 选择商品
	_confirmPress = (data) => {
		this.setHeaderInfo(data[0].rptId, data[0].rptName, data[0].rptItem.attentionFlag);
		console.log('180data', data);
		if (data && data.length > 0) {
			this.setState({
				rptTypesModal: false,
				curRptId: data[0].rptId,
				curRptName: data[0].rptName,
				attentionFlag: data[0].rptItem.attentionFlag,
			}, async () => {
				let lastrptId = sendData.rptId;
				if (lastrptId == data[0].rptId) return;
				sendData.rptId = data[0].rptId;
				sendData.rptName = data[0].rptName;
				navData.item.rptId = data[0].rptId;

				this._setUrl(data[0].rptId);
			})
		} else {
			this.setState({ rptTypesModal: false })
		}


	}

	//商品取消按钮
	_cancelPress = (data) => {
		this.setState({ rptTypesModal: false })
	}


	async _collect (id) {
		const { reportsList } = this.state;
		//点击收藏、取消收藏
		await request.collect(id);
		this.setHeaderInfo(this.state.curRptId, this.state.curRptName, !this.state.attentionFlag);
		reportsList.map((item, index) => {
			return item.children.map((child, index1) => {
				if (child.rptId === id) {
					child.attentionFlag = !this.state.attentionFlag;
				}
			})
		})

		this.setState({
			attentionFlag: !this.state.attentionFlag,
			reportsList
		})
	}

	toggleReportTypes () {
		let { rptTypesModal } = this.state;
		this.setState({ rptTypesModal: !rptTypesModal })
	}

	//查询面板打开隐藏
	toggleFilterModal = () => {
		let { filterInfoBoxWidth, filterInfoOpenWidth, rptFilterModal } = this.state;

		rptFilterModal = !rptFilterModal;
		Animated.timing(filterInfoBoxWidth, {
			duration: 300,
			toValue: rptFilterModal ? filterInfoOpenWidth : 0,
		}).start();
		this.setState({ rptFilterModal })
	}


	_loadError (e) {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status='error' onErrorPress={() => this._setUrl(this.state.curRptId)} />
			</View>
		)
	}

	handleMessage (e) {
		if (e.nativeEvent.data) {
			let filterData = e.nativeEvent.data;
			let start = filterData.indexOf('&');
			filterData = start === -1 ? '' : filterData.substr(start);

			this._setUrl(this.state.curRptId);
			this.setState({ filterData })
		}
	}

	render () {
		const { webViewUrl, filterWebViewUrl, rptTypesModal, filterInfoBoxWidth, filterData } = this.state;
		const webview = WebView;
		let ProductSend = [];
		if (sendData.rptId) {
			ProductSend.push({ rptId: sendData.rptId, rptName: sendData.rptName })
		}
		return (
			<View style={[styles.container]}>
				{/**报表主体 */}
				<View style={styles.container}>
					{/* <View
					{...this._panResponder.panHandlers}
						style={[{
							backgroundColor: 'red',
							width: 200,
							height: 200,
							borderWidth: 1,
							borderColor: 'black',
							position: 'absolute',
							left: this.state.left
						}]}></View> */}
					<WebView
						ref={'webview'}
						source={
							{
								uri: webViewUrl,
								headers: {
									'Accept': 'application/json',
									'Content-Type': 'application/json',
									"authToken": GLOBAL.TOKEN
								}
							}
						}
						style={{ width: '100%', height: '100%' }}
						onMessage={(e) => {
							this._handleMessage(e)
						}}
						onLoadEnd={(e) => {
						}}
						renderError={(e) => this._loadError(e)}
						onError={(e) => this._loadError(e)}
						startInLoadingState={true}
					/>
				</View>

				{/**底部报表类型 */}
				<View style={[{ position: 'absolute', bottom: 0, width: '100%' }]}>
					<BoxShadow setting={shadowOpt}>
						<TouchableOpacity activeOpacity={1} style={styles.toggleImg} onPress={() => this.toggleReportTypes()}>
							<Image style={[styles.imgStyle]} source={bottomImg}></Image>
						</TouchableOpacity>
						<View style={{ backgroundColor: '#fff', width: '100%', height: 34 * scale }}></View>
					</BoxShadow>
					{
						this.state.reportsList && this.state.reportsList.length > 0 ?

							<View style={{ backgroundColor: '#fff', width: '100%' }}>
								<SelectComponent
									cancelPress={this._cancelPress}
									confirmPress={this._confirmPress}
									sendData={this.state.reportsList}
									mainCheckData={ProductSend}
									modalVisible={rptTypesModal} />
							</View>
							: null
					}
				</View>

				{/**左侧查询面板 */}
				<Animated.View style={[styles.filterContainer, { width: filterInfoBoxWidth, overflow: 'hidden' }]}>
					<View style={{ width: '80%', height: '100%', position: 'absolute', right: 0, backgroundColor: '#fff' }}>
						<WebView
							ref={'webview'}
							source={{
								uri: filterWebViewUrl,
								headers: {
									'Accept': 'application/json',
									'Content-Type': 'application/json',
									"authToken": GLOBAL.TOKEN
								}
							}}
							style={{ width: '100%', height: '100%' }}
							onMessage={(e) => {
								this.handleMessage(e)
							}}
							renderError={(e) => this._loadError(e)}
							onError={(e) => this._loadError(e)}
							onLoadEnd={() => {
								this.refs.webview.postMessage(filterData);
							}}
							startInLoadingState={true}
						/>
					</View>
				</Animated.View>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1
	},
	toggleImg: {
		flexDirection: 'row',
		justifyContent: 'center',
	},
	imgStyle: {
		position: 'absolute',
		top: -25 * scale,
		width: 72 * scale,
		height: 26 * scale,
		zIndex: 99
	},
	filterContainer: {
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		position: 'absolute',
		right: 0,
		top: 0
	},
})